name: Generate PR Description

on:
  issue_comment:
    types: [created]

jobs:
  generate-pr-description:
    permissions:
      pull-requests: write
      statuses: write
    runs-on: ubuntu-latest
    if: github.event.issue.pull_request && contains(github.event.comment.body, '/sk generate-pr-description')
    steps:
      - name: Get PR branch
        uses: xt0rted/pull-request-comment-branch@v1
        id: comment-branch

      - name: Set latest commit status as pending
        uses: myrotvorets/set-commit-status-action@master
        with:
          sha: ${{ steps.comment-branch.outputs.head_sha }}
          token: ${{ secrets.GITHUB_TOKEN }}
          status: pending

      - name: Generate PR description
        uses: mkarle/skonsole-generate-pr-description@v1
        with:
          pull-request-number: ${{ github.event.issue.number }}
          pull-request-diff-url: ${{ github.event.issue.pull_request.diff_url }}
          token: ${{ secrets.GITHUB_TOKEN }}
          update-type:  ${{ contains(github.event.comment.body, 'replace') && 'replace' || (contains(github.event.comment.body, 'prefix') && 'prefix' || 'suffix') }}
        env: # Set Azure credentials secret as an input
          AZURE_OPENAI_CHAT_DEPLOYMENT_NAME: ${{ vars.AZUREOPENAI__CHAT__DEPLOYMENTNAME }}
          AZURE_OPENAI_API_ENDPOINT: ${{ secrets.AZUREOPENAI__ENDPOINT }}
          AZURE_OPENAI_API_KEY: ${{ secrets.AZUREOPENAI__APIKEY }}
      
      - name: Set latest commit status as ${{ job.status }}
        uses: myrotvorets/set-commit-status-action@master
        if: always()
        with:
          sha: ${{ steps.comment-branch.outputs.head_sha }}
          token: ${{ secrets.GITHUB_TOKEN }}
          status: ${{ job.status }}

      - name: Add comment to PR
        uses: actions/github-script@v6
        if: always()
        with:
          script: |
            const name = '${{ github.workflow   }}';
            const url = '${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}';
            const success = '${{ job.status }}' === 'success';
            const body = `${name}: ${success ? 'succeeded ✅' : 'failed ❌'}\n${url}`;

            await github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: body
            })
